#include "Arduino.h"
#include "espweb.h"
#include "esplog.h"
#include "espsettings.h"
#include "espwificonfig.h"
#include "httpserver.h"
#include "commands/command.h"
#include "espuser.h"
#include "espwebsocket.h"
bool EspWeb::restart = false;
// Contructor

EspWeb::EspWeb()
{
}

void settingReset()
{
    log_debug("Need reset settings");
    if (!Settings::reset())
    {
        log_debug("Reset settings error");
    }
    // 重启
    log_debug("Restarting");
    ESP.restart();
    while (1)
    {
        delay(1);
    }
}

// Begin which setup everything
bool EspWeb::begin()
{
    bool res = true;
    // 初始化日志输出
    initLog();
    log_debug("log init end");
    log_debug("disenable wifi");
    WiFiConfig::end();
    log_debug("Mode %d", WiFi.getMode());

    if (!Settings::begin())
    {
        settingReset();
    }

    // 开启WIFI
    int8_t mode = Settings::readByte(KEY_RADIO_MODE);

    log_debug("wifi mode:%d", mode);
    // 配置异常，恢复默认
    if (mode < WIFI_OFF || mode > WIFI_AP_STA)
        settingReset();
    if (!WiFiConfig::begin(mode))
    {
        log_error("Error setup network");
        res = false;
    }
    // http服务
    if (!HTTP_Server::begin())
    {
        res = false;
        log_error("HTTP server failed");
    }
    else
    {
        if (HTTP_Server::started())
        {
            String stmp = "HTTP server started port " + String(HTTP_Server::port());
            log_debug("%s", stmp.c_str());
        }
    }
    log_debug("start websocket");

    EspWebsocket::begin();
    EspUser::begin();
    return res;
}
// Process which handle all input
void EspWeb::handle()
{
    if (restart)
    {
        restart_now();
    }
    HTTP_Server::handle();
    EspWebsocket::handle();
    EspUser::handle();
}
// Set Restart flag
void EspWeb::restart_esp(bool need_restart)
{
    restart = need_restart;
}

void EspWeb::restart_now()
{

    log_debug("Restarting");

#if defined(FILESYSTEM_FEATURE)
    ESP_FileSystem::end();
#endif // FILESYSTEM_FEATURE
    ESP.restart();
    while (1)
    {
        delay(1);
    }
}
